package cn.yi.fast.mq.rocketmq.service.impl;

import cn.yi.fast.mq.rocketmq.coder.MessageEncoder;
import cn.yi.fast.mq.rocketmq.manager.DefaultMessageProducerManager;
import cn.yi.fast.mq.rocketmq.message.AbstractMessage;
import cn.yi.fast.mq.rocketmq.message.DefaultMessage;
import cn.yi.fast.mq.rocketmq.service.MessageProducerService;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.client.producer.SendStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

@Service
public class MessageProducerServiceImpl implements MessageProducerService {


    @Autowired(required = false)
    private DefaultMessageProducerManager producerManager;
    @Autowired(required = false)
    @Qualifier("messageEncoder")
    private MessageEncoder<Map<String,Object>> encoder;

    public void send(String  topic,String tag,String key,Map<String,Object> data,SendFail sendFail){

        boolean sendSuccess;

        AbstractMessage<Map<String,Object>> message = new DefaultMessage<>(topic,tag,key,data,encoder);
        SendResult sendResult = producerManager.sendMessage(message);
        sendSuccess = Objects.equals(sendResult.getSendStatus(), SendStatus.SEND_OK);

        if(!sendSuccess){
            sendFail.run();
        }
    }


}
